#pragma once
#include <iostream>
#include <string>
#include <stdint.h>
#include <cstring>
#include "log.hpp"
#include "Init.hpp"

Init init;
const int DATASIZE = 4096;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : _socket(sockfd), _ip(clientip), _port(clientport)
    {
    }
    Task()
    {
    }
    void run()
    {
        char buffer[DATASIZE];
        // 接收数据
        memset(buffer, 0, sizeof(buffer));
        ssize_t n = read(_socket, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;

            // 向客户端响应数据
            std::string echo_string = init.translation(buffer);
            n = write(_socket, echo_string.c_str(), sizeof(echo_string));
            if (n < 0)
            {
                tcplg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            tcplg(Info, "%s:%d quit, server close sockfd: %d", _ip.c_str(), _port, _socket);
        }
        else if (n == -1)
        {
            tcplg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _socket, _ip.c_str(), _port);
            perror("read fail");
        }
        close(_socket);
    }
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }

private:
    int _socket;
    uint16_t _port;
    std::string _ip;
};